<template>
  <div class="order_detail" v-loading="loading">
    <div class="detail_head">
      <div class="head_left">
        <span>订单编号：{{ detailInfo.orderNo }}</span>
        <span>下单时间：{{ detailInfo.orderTime }}</span>
        <span>
          付款状态：
          <span :class="`state_tag state_tag__state${detailInfo.payStatus}`">
            {{ dict.getDictName("shop_pay_status", detailInfo.payStatus) }}
          </span>
        </span>
      </div>
      <div class="head_right">
        <el-button type="primary" link @click="goBack()">返回</el-button>
      </div>
    </div>
    <div class="detail_content">
      <div class="content_top">
        <div :class="`top_title top_title__state${detailInfo.purchaseStatus}`">
          {{ purchaseStateList[detailInfo.purchaseStatus - 1] }}
        </div>
        <div class="top_tip" v-if="[1, 2].indexOf(detailInfo.purchaseStatus) > -1">
          如需要将当前订单取消，请联系工程核量员，撤销订单，如有已发起采购的商品，将不能撤销合同订单~~
        </div>
        <div class="top_info_box">
          <div class="info_label">采购商信息</div>
          <div class="info_text mb12">{{ detailInfo.purchaseName }}</div>
          <div class="info_label">客户信息</div>
          <div class="info_text mb12">
            <div>姓名:{{ detailInfo.customerName }}</div>
            <div>电话:{{ detailInfo.customerMobileCode }}</div>
            <div>项目地址：{{ detailInfo.customerAddress }}</div>
          </div>
          <div class="info_label">收货信息</div>
          <div class="info_text mb12">
            <div>姓名:{{ detailInfo.receivingName }}</div>
            <div>电话:{{ detailInfo.receivingMobile }}</div>
            <div>
              收货地址：{{ `${detailInfo.receivingAreaDetail || ""}${detailInfo.receivingAddress || ""}` }}
              <el-button v-if="isEdit" class="ml10" type="primary" link @click="openUpdateReceiptInfoModal(detailInfo)">
                修改
                <img class="ml10" style="width: 16px; height: 16px" src="@/assets/images/edit.png" />
              </el-button>
            </div>
          </div>
          <div class="info_label">订单备注</div>
          <div class="info_text">
            <RemarkEditor v-model="detailInfo.remark" :showCancel="false" :isEdit="isEdit" @submit="updateRemark()">
              <template #edit="scope">
                <el-button v-if="scope.isEdit" class="ml10" type="primary" link>
                  修改
                  <img class="ml10" style="width: 16px; height: 16px" src="@/assets/images/edit.png" />
                </el-button>
              </template>
            </RemarkEditor>
          </div>
        </div>
      </div>
      <div class="content_bottom">
        <div class="bottom_title" style="display: flex; justify-content: space-between">总价：¥{{ detailInfo.totalPrice }}</div>
        <div class="bottom_info_box mt12">
          <span>折扣金额：¥{{ detailInfo.profitFee }}</span>
          <span>优惠金额：¥{{ detailInfo.discountAmount }}</span>
          <span>其他费用：¥{{ detailInfo.otherFee }}</span>
          <span>应付金额：¥{{ detailInfo.payableTotalAmount }}</span>
          <span>未付金额：¥{{ detailInfo.remainTotalAmount }}</span>
          <span style="font-weight: 700">
            实付金额：<span style="color: #ff3333">¥{{ detailInfo.actualTotalAmount }}</span>
          </span>
        </div>
        <div class="bottom_title mt24 mb12">商品信息</div>
        <el-table
          border
          :data="detailInfo.orderDetailGroup"
          style="width: 100%"
          header-cell-class-name="table_head"
          :cell-class-name="isSheftClass"
        >
          <el-table-column label="商品信息" min-width="100px">
            <template #default="{ row }">
              <div class="goods_cell ml30">
                <div class="cell_image_box">
                  <img class="cell_image jzt-cursor-point" :src="row.mainPicUrl" @click="toProdDetail(row)" />
                  <span class="cell_image_tag" v-if="row.isSheft === 0"> 已下架 </span>
                  <el-popconfirm v-if="row.isSheft === 0" title="确认删除商品吗?" @confirm="deleteProduct(row)">
                    <template #reference>
                      <div class="cell_image_close">
                        <el-icon @click="handleRemove(index)"><Close /></el-icon>
                      </div>
                    </template>
                  </el-popconfirm>
                  <div class="custom-fixed-icon" v-if="row.isCustom === 1">
                    <img src="@/assets/images/custom-icon.png" alt="" width="48" height="43" />
                  </div>
                </div>
                <div class="cell_product">
                  <div class="product_name jzt-cursor-point" @click="toProdDetail(row)">
                    {{ row.productAliasName }}
                  </div>
                  <div class="product_info">{{ row.skuSpecification }}</div>
                  <div class="product_info">SKU编码:{{ row.skuCode }}</div>
                  <div class="product_info">ID：{{ row.productId }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="商品价格" align="center" width="100px">
            <template #default="{ row }"> ¥{{ row.unitPrice }} </template>
          </el-table-column>
          <el-table-column prop="commodityNum" label="数量" align="center">
            <template #default="{ row }">
              {{ row.commodityNum }}
            </template>
          </el-table-column>
          <el-table-column prop="detailNum" label="商品件数" align="center" width="100px">
            <template #default="{ row }">
              {{ row.detailNum }}
            </template>
          </el-table-column>
          <el-table-column prop="productUnit" label="单位" align="center" width="100px">
            <template #default="{ row }">
              {{ dict.getDictName("shop_unit", row.productUnit) }}
            </template>
          </el-table-column>
          <el-table-column prop="actualPrice" label="销售价格" align="center">
            <template #default="{ row }"> ¥{{ row.actualPrice }} </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <UpdateReceiptInfoDialog
      v-if="updateReceiptInfoFlag"
      v-model="updateReceiptInfoFlag"
      :orderDetail="detailInfoCache"
      @success="successHandle"
    />
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import { deleteOrderSku, delOrder, getOrderDetail, updateOrderInfo } from "@/apis/order";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
import { ElMessage } from "element-plus";
import { publicTotal2 } from "@/utils/summation";
import useCodeArrStore from "@/store/modules/select";
const dict = useCodeArrStore();
import RemarkEditor from "@/components/RemarkEditor";
import UpdateReceiptInfoDialog from "./components/updateReceiptInfoDialog.vue";

// 订单采购状态; 1:待采购 2:部分采购 3:已采购 4：已撤销
const isEdit = computed(() => detailInfo.value.purchaseStatus === 1 || detailInfo.value.purchaseStatus === 2);
const purchaseStateList = ["待采购", "部分采购", "已采购", "已撤销"];
const detailInfo = ref({});
const detailInfoCache = ref({});
const updateReceiptInfoFlag = ref(false);
const orderId = route.query.orderId;
const loading = ref(false);

onMounted(() => {
  getDetailInfo();
});

const toProdDetail = row => {
  console.log("跳转到商品详情页");
  const baseRouter = window.microApp.router.getBaseAppRouter();
  const routeUrl = baseRouter.resolve({
    path: "/designer/shopDetail/index",
    query: { id: row?.productId }
  });
  window.open(routeUrl.href, "_blank");
};

const goBack = () => router.push({ path: "/manage/orderlist", query: { purchaseStatus: detailInfo.value.purchaseStatus } });

const openUpdateReceiptInfoModal = item => {
  let ids = [];
  if (item.receivingAreaIds) {
    ids = item.receivingAreaIds.split(",");
  }
  detailInfoCache.value = JSON.parse(
    JSON.stringify({
      ...item,
      receivingAreaIds: ids
    })
  );
  updateReceiptInfoFlag.value = true;
};

const updateRemark = async () => {
  await updateOrderInfo({
    orderId,
    remark: detailInfo.value.remark
  });
  successHandle("修改备注成功");
};

const successHandle = (msg, isRefresh = true) => {
  ElMessage({ message: msg, type: "success" });
  isRefresh && getDetailInfo();
};

const getDetailInfo = async () => {
  loading.value = true;
  const { data } = await getOrderDetail(orderId);
  data.orderDetailGroup = convertData(data.orderDetailGroup);
  data.totalPrice = publicTotal2(data.orderDetailList).toFixed(2);
  detailInfo.value = data;
  loading.value = false;
  console.log("订单详情数据===", data);
};

const convertData = arr => {
  const newArr = [];
  arr.forEach(factory => {
    factory.list.forEach(product => {
      newArr.push({
        ...factory,
        ...product
      });
    });
  });
  return newArr;
};

const isSheftClass = ({ row, columnIndex }) => {
  if (row.isSheft === 0 && [0, 8].indexOf(columnIndex) < 0) {
    if (columnIndex !== 1) return "sheft_cell";
    else return "image_sheft_cell";
  }
};
</script>

<style lang="scss" scoped>
.order_detail {
  width: 100%;
  height: calc(100vh - 156px);
  border-radius: 10px;
  .custom-fixed-icon {
    position: absolute;
    top: -7px;
    left: -32px;
  }
  .detail_head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    height: 60px;
    border-bottom: 1px solid #d8d8d8;
    position: sticky;
    top: 0;
    .head_left {
      display: flex;
      gap: 32px;
      font-size: 12px;
      .state_tag {
        padding: 1px 10px;
        &__state1 {
          color: #ff9900;
          background: #fff0d9;
        }
        &__state2 {
          color: #007dff;
          background-color: #d9edff;
        }
        &__state3 {
          color: #14c85c;
          background-color: #f0f9eb;
        }
      }
    }
    .head_right {
      display: flex;
      align-items: center;
      gap: 20px;
      .split_line {
        width: 4px;
        height: 18px;
        background: #e1e6ed;
        border-radius: 2px 2px 2px 2px;
      }
    }
  }
  .detail_content {
    background: #f5f7fa;
    box-sizing: border-box;
    height: calc(100% - 60px);
    overflow: auto;
    .content_top {
      padding: 20px;
      display: grid;
      gap: 12px;
      background: white;
      .top_title {
        font-size: 24px;
        line-height: 34px;
        text-transform: none;
        &__state1 {
          color: #ff9900;
        }
        &__state2 {
          color: #007dff;
        }
        &__state3 {
          color: #14c85c;
        }
      }
      .top_tip {
        color: #86909c;
        line-height: 20px;
      }
      .top_info_box {
        display: grid;
        gap: 10px;
        padding: 20px;
        background: #f6f8fa;
        .info_label {
          font-size: 16px;
          color: #86909c;
          line-height: 24px;
        }
        .info_text {
          display: flex;
          gap: 160px;
        }
      }
    }
    .content_bottom {
      background: white;
      margin-top: 20px;
      padding: 20px;
      .bottom_title {
        font-size: 18px;
        color: #1a1a1a;
        line-height: 25px;
      }
      .bottom_info_box {
        display: flex;
        gap: 70px;
        padding: 20px;
        background: #f6f8fa;
      }
      :deep(.table_head) {
        background-color: #f2f6fc !important;
      }
      .factory_cell {
        display: flex;
        flex-direction: column;
        justify-content: center;
        .cell_label {
          color: #4e5969;
        }
        .cell_text {
          color: #1a1a1a;
          line-height: 20px;
          margin-bottom: 10px;
        }
      }
      .sheft_cell {
        opacity: 0.5;
      }
      .image_sheft_cell {
        padding: 0;
        .goods_cell {
          padding: 10px 0;
          .cell_image,
          .cell_product {
            opacity: 0.5;
          }
        }
        .cell_image_tag {
          position: absolute;
          left: 0;
          bottom: 0;
          width: 100%;
          color: white;
          background: #4e5969;
          font-size: 12px;
          text-align: center;
          border-radius: 0px 0px 5px 5px;
          opacity: 1 !important;
          z-index: 10;
        }
        .cell_image_close {
          position: absolute;
          left: -4px;
          top: -4px;
          display: flex;
          justify-content: center;
          align-items: center;
          height: 16px;
          width: 16px;
          border-radius: 50%;
          background: red;
          color: #fff;
          outline: 2px solid;
        }
      }
      .goods_cell {
        display: grid;
        grid-template-columns: 80px calc(100% - 100px);
        gap: 20px;
        position: relative;
        .cell_image_box {
          position: relative;
          .cell_image {
            width: 80px;
            height: 80px;
            border-radius: 4px;
          }
        }
        .cell_product {
          .product_name {
            color: #3d3d3d;
            font-weight: 700;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 24px;
          }
          .product_info {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 12px;
            color: #86909c;
            line-height: 20px;
          }
        }
      }
      .lock_num {
        display: flex;
        justify-content: center;
        align-items: center;
        max-width: 50px;
        margin: 0 auto;
        background: #f2f3f5;
        border-radius: 4px;
      }
      .grey_box {
        position: relative;
        display: grid;
        gap: 10px;
        right: 12px;
        width: calc(100% + 24px);
        padding: 10px;
        text-align: center;
        font-size: 12px;
        background: #f6f8fa;
      }
    }
  }
}
</style>
